//
//  YBXueTangInputController.m
//  孕妙
//
//  Created by Raoy on 16/4/11.
//  Copyright © 2016年 是源科技. All rights reserved.
//

#import "YBXueTangInputController.h"
#import "YBSelectPickerWindow.h"
#import <CoreBluetooth/CoreBluetooth.h>

#define SERVICEUUID @"1000"//服务UUID
#define WRITEUUID @"1001"//写入UUID
#define NOTIFYUUID @"1002"//读取UUID

@interface YBXueTangInputController ()<UIPickerViewDelegate, UIPickerViewDataSource, CBCentralManagerDelegate, CBPeripheralDelegate>
//弹出手动输入窗口
@property (strong, nonatomic) YBSelectPickerWindow *pickerWindow;
@property (strong, nonatomic) CBCentralManager *mgr;
@property (strong, nonatomic) CBCharacteristic *characteristic;
@property (strong, nonatomic) NSMutableArray *periperals;
//当前外设
@property (strong, nonatomic) CBPeripheral *peripheral;
@property (nonatomic, getter=isGetStartMeasure) BOOL getStartMeasure;
@end

@implementation YBXueTangInputController
{
    NSMutableArray *intArray; //选择器整数部分
    NSArray *floatArray;   //选择器小数部分
    NSString *valueStr;  //设置string格式
    NSString *selectIntStr;  //获取整数值
    NSString *selectFloatStr;  //获取小数值
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor =  SYColor(245, 245, 245);;
    self.title = @"记录血糖";
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"YB_backToSupper"  highIcon:nil target:self action:@selector(clickLeftButtonToSupper2:)];
    self.navigationItem.rightBarButtonItem =  [[UIBarButtonItem alloc] initWithCustomView:self.rightBtn];
    
    [self.rightBtn addTarget:self action:@selector(righeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self scanBle];
    //开始使用蓝牙设备测量
    [self.startbtn2 addTarget:self action:@selector(openBle:) forControlEvents:UIControlEventTouchUpInside];
    
    intArray = [NSMutableArray array];
    //设置小数，整数范围
    floatArray = @[@"0", @"1", @"2", @"3", @"4",@"5", @"6", @"7",@"8", @"9"];

    for (int index = 2; index <= 33; index++) {
        NSString *str = [NSString stringWithFormat:@"%d", index];
        [intArray addObject:str];
    }
    //设置日期栏
    [self setTitle:@"请输入血糖:" buyTitle:@"购买血糖仪" indexImage:3];
    valueStr = @" mmol/L";
    //设置血糖
    [self createLabel:valueStr];
    // Do any additional setup after loading the view.
}

- (void)righeBtnClick:(id)sender
{
    self.fuGaiView.hidden = NO;
    if (_pickerWindow == nil) {
        _pickerWindow = [[YBSelectPickerWindow alloc] init];
        [_pickerWindow addSubview:_pickerWindow.dianL];
        [_pickerWindow setInterFace:@"血糖(mmol/L)"];
        
         [_pickerWindow addSubview:_pickerWindow.dianL];
        _pickerWindow.selectPickerView.delegate = self;
        _pickerWindow.selectPickerView.dataSource = self;
    }else{
        
        _pickerWindow.hidden = NO;
    }
    [_pickerWindow.selectPickerView selectRow:4 inComponent:0 animated:YES];
    [_pickerWindow.selectPickerView selectRow:0 inComponent:1 animated:YES];
    selectIntStr = intArray[4];
    selectFloatStr = floatArray[0];
    [_pickerWindow.sureBtn addTarget:self action:@selector(saveDataBtn:) forControlEvents:UIControlEventTouchUpInside];
    [_pickerWindow.cancelBtn addTarget:self action:@selector(cancelBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
}

//- (void)callBlock:(ItemValueblock)block
//{
//    self.valueBlock = block;
//}
- (void)openBle:(UIButton *)button
{
    //    tiwenOncetoken = 0;
    [self scanBle];
    
}
//对象的视图已经加入到窗口时调用
- (void)viewDidAppear:(BOOL)animated
{
    NSLog(@"sfeawrr------");
    [super viewDidAppear:YES];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
}

/*
  手动输入窗口的保存按钮
*/

- (void)saveDataBtn:(UIButton *)button
{
    valueStr = nil;
    self.fuGaiView.hidden = YES;
    self.pickerWindow.hidden = YES;
    valueStr = [NSString stringWithFormat:@"%@.%@ mmol/L", selectIntStr, selectFloatStr];
    [self createLabel:valueStr];
    [self.view setNeedsDisplay];
    
    [self getUserParmaterData:[NSString stringWithFormat:@"%@.%@", selectIntStr, selectFloatStr] selectionValue:3 gaoxueya:nil];
    
}

- (void)cancelBtnClicked:(id)sender
{
    self.fuGaiView.hidden = YES;
}

- (void)clickLeftButtonToSupper2:(id)sender
{
    _pickerWindow = nil;  //释放内存
    NSLog(@"%@", valueStr);
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UIPickerView
//选择框代理方法
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == 0) {
        return intArray.count;
    } else {
        return floatArray.count;
    }
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (component == 0) {
        return  intArray[row];
    } else {
        return  floatArray[row];
    }
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (component == 0) {
        selectIntStr = intArray[row];
    } else {
        selectFloatStr = floatArray[row];
    }
    
}
#pragma -mark 蓝牙连接外设
- (NSMutableArray *)peripherals
{
    if (!_periperals) {
        _periperals = [NSMutableArray array];
    }
    return _periperals;
}

- (CBCentralManager *)mgr
{
    if (!_mgr) {
        self.mgr = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    }
    
    return _mgr;
}

- (void)scanBle
{
    self.startbtn2.isAccessibilityElement = NO;
    [MBProgressHUD showMessage:@"正在搜索设备......"];
    [self.mgr stopScan];
    [self.mgr scanForPeripheralsWithServices:nil options:nil];
    self.startbtn2.isAccessibilityElement = YES;
}

#pragma -mark CBCentralManagerDelegate

//检查设备是否支持BLE
-(void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    switch (central.state) {
        case CBCentralManagerStatePoweredOn:// 蓝牙打开
            NSLog(@"CBCentralManagerStatePoweredOn");
            [self.mgr scanForPeripheralsWithServices:nil options:nil];
            break;
        case CBCentralManagerStatePoweredOff://蓝牙关闭
            NSLog(@"CBCentralManagerStatePoweredOff");
            break;
        case CBCentralManagerStateUnsupported:
            NSLog(@"State Unsupported");
            break;
        default:
            NSLog(@"Central Manager Did Update State");
            break;
    }
}

//发现外设调用
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(nonnull CBPeripheral *)peripheral advertisementData:(nonnull NSDictionary<NSString *,id> *)advertisementData RSSI:(nonnull NSNumber *)RSSI
{
    NSLog(@"发现外设：%@  ", peripheral.name);
    
    [MBProgressHUD hideHUD];
    
    if (![self.peripherals containsObject:peripheral]&& [peripheral.name hasPrefix:@"Bioland"]){
        
        //设置外设代理
        peripheral.delegate = self;
        [self.peripherals addObject:peripheral];
    }else{
        
        return;
    }
    
    NSLog(@"找到了 %@", peripheral.name);
    
    for (CBPeripheral *per in self.peripherals) {
        NSLog(@"外设：%@", per);
        if (per.state == NO) {
            self.peripheral = peripheral;
            [self.mgr connectPeripheral:self.peripheral options:nil];
        }
    }
    
}

//连接到外设的时候调用
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(nonnull CBPeripheral *)peripheral
{
    NSLog(@"连接外设成功");
    [self.mgr stopScan];
    
    // 查找外设中的所有服务
    //#warning 通过传入一个存放服务UDID的数组进去，过滤掉一些不要的服务
    [peripheral discoverServices:nil];
}

//连接外设失败
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(nonnull CBPeripheral *)peripheral error:(nullable NSError *)error
{
    [MBProgressHUD showError:@"连接设备失败, 请重新连接"];
    [self.mgr scanForPeripheralsWithServices:nil options:nil];
    [self.peripherals removeAllObjects];

}

//跟设备失去连接

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    self.peripheral = nil;
    [self.peripherals removeAllObjects];
    self.getStartMeasure = NO;
    [self.buletoothImageView setImage:[UIImage imageNamed:@"蓝牙断开"]];
    // 扫描
    [self.mgr scanForPeripheralsWithServices:nil options:nil];
    [self.peripherals removeAllObjects];
    NSLog(@"蓝牙断开didDisconnectPeripheral");
}

#pragma mark - CBPeripheralDelegate
//已连接外设，配对服务

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
    NSLog(@"发现服务  %@", peripheral.services);
    // 遍历所有的服务
    for (CBService *service in peripheral.services) {
        // 过滤其他服务, 匹配自己想要的服务
        if ([service.UUID isEqual:[CBUUID UUIDWithString:SERVICEUUID]]) {
            
            //#warning 通过传入一个存放特征UDID的数组进去，过滤掉一些不要的特征
            [peripheral discoverCharacteristics:nil forService:service];
        }
    }
}

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
    NSLog(@"didDiscoverCharacteristicsForService: %@", service.characteristics);
    [self.buletoothImageView setImage:[UIImage imageNamed:@"蓝牙连接"]];
    [self.view setNeedsDisplay];
    
    [self.peripherals removeAllObjects];
    // 遍历所有的特征
    for (CBCharacteristic *characteristic in service.characteristics) {
        NSLog(@"--%@---", characteristic.UUID);
        
        //过滤不想要的特征
        if([characteristic.UUID isEqual:[CBUUID UUIDWithString:NOTIFYUUID]]){
            NSLog(@"--已找到特征1002, 注册监听  ");
            [peripheral setNotifyValue:YES forCharacteristic:characteristic];
        }

        
        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:WRITEUUID]]) {
            NSLog(@"--已找到特征1001 ,发数据到外设 ");
            self.characteristic = characteristic;

                [self requestXTDatatoBlue:characteristic];
            
            }
    }
}

//外设接收数据
- (void) requestXTDatatoBlue:(CBCharacteristic *)achar
{
    Byte bytes[11];
    bytes[0] = 0x5A;
    bytes[1] = 0x0B;
    bytes[2] = 0x05;
    bytes[3] = 0x10;
    bytes[4] = 0x09;
    bytes[5] = 0x06;
    bytes[6] = 0x0A;
    bytes[7] = 0x0C;
    bytes[8] = 0x9F;
    bytes[9] = 0x00;
    bytes[10] = 0x00;

    NSData *bytedata = [[NSData alloc] initWithBytes:bytes length:11];
    NSLog(@"发送血糖数据给蓝牙: %@",bytedata);
    [self.peripheral writeValue:bytedata forCharacteristic:achar type:CBCharacteristicWriteWithoutResponse];
}

- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    
    if (error)
    {
        NSLog(@"didUpdateValueForCharacteristicError: %@", error.localizedDescription);
        return;
    }
    
    if([characteristic.UUID isEqual:[CBUUID UUIDWithString:NOTIFYUUID]])
    {
#pragma mark 接收处理数据
        NSLog(@"接收数据: %@",characteristic.value);
        // 接收到蓝牙数据 先分析 再回传给代理 最后发送指令关机
        [self analyseData:characteristic.value withPeripheral:peripheral];

    }
}

// 接收到蓝牙数据进行分析判断
- (void)analyseData:(NSData *)data withPeripheral:(CBPeripheral *)aPer
{
    
    Byte *bytes = (Byte *)[data bytes];
    
    switch (bytes[2]) {
        case 0x00:
        {
            //根据协议说明 00为信息包需再次发送应答包 然后返回给结果包。
            [self requestXTDatatoBlue:self.characteristic];
            break;
        }
            case 0x03:
        {
            //03为结果包。
            float SYSValue = bytes[9];
            valueStr = [NSString stringWithFormat:@"%.1f  mmol/L", SYSValue / 18];
            [self createLabel:valueStr];
            [self.view setNeedsDisplay];
            //上传数据到服务器
            [self getUserParmaterData:[NSString stringWithFormat:@"%.1f",SYSValue / 18] selectionValue:3 gaoxueya:nil];
        }
        default:
            break;
    }
}
@end